import TrtcCloud from "@/TrtcCloud/lib/index";
import {
  TRTCAppScene,
  TRTCVideoStreamType,
  TRTCAudioQuality,
  TRTCAudioRoute
} from "@/TrtcCloud/lib/TrtcDefines";

import { TRTCRoleType } from "@/TrtcCloud/lib/TrtcDefines";

// import TrtcLocalView from '@/TrtcCloud/view/TrtcLocalView';
const trtcCloud = TrtcCloud.createInstance();

import { getUserSign, outRoom, checkRoom } from "@/common/api/index.js";
// 悬浮窗插件
const LinFloatWeb = uni.requireNativePlugin("Lin-Accessibility-Float");
const systemInfo = uni.getSystemInfoSync();
const width = systemInfo.windowWidth;
const height = systemInfo.windowHeight;

module.exports = {
  data() {
    return {
      trtcParms: {
        sdkAppId: "",
        userId: "",
        strRoomId: "",
        userSig: "",
        role: TRTCRoleType.TRTCRoleAnchor,
        isCreate: false, // 是否创建房间
      },
      get_friend_id: "",
      runEndFunc: null,
    };
  },
  onLoad() {},
  onExit() {
    uni.$off("takeTrtc");
    uni.$off("linkTrtc");
    trtcCloud.exitRoom();
  },
  async created() {
    console.log("监听成功");
    let that = this;

    // 通过通知创建链接
    uni.$on("takeTrtc", (res) => {
      that.get_friend_id = res.data.send_user_id;
      that.isCreate = true;
      that.startLocalPreview();
      trtcCloud.enterRoom(that.trtcParms, TRTCAppScene.TRTCAppSceneVideoCall);
    });

    // 直接链接
    uni.$on("trtc_linkTrtc", (res) => {
      that.trtcParms.strRoomId = res.roomId;
      that.runEndFunc = res.event;
      that.startLocalPreview();
      trtcCloud.enterRoom(that.trtcParms, TRTCAppScene.TRTCAppSceneVideoCall);
    });

    trtcCloud.on("onEnterRoom", (result) => {
      if (result > 0 && that.isCreate) {
        console.log(`创建房间成功，耗时: ${result}ms`);
        let userId = that.$store.state.userInfo.id;
        console.log(userId, that.get_friend_id);
        that.$store.commit("publishMessage", {
          topic: `${userId}_${that.get_friend_id}`,
          msg: JSON.stringify({
            todo: "linkTrtc",
            data: {
              roomId: that.trtcParms.strRoomId,
            },
          }),
        });
      }
      if (result > 0 && !that.isCreate) {
        console.log(`进房成功，耗时: ${result}ms`);
        //进房成功 关闭悬浮窗
        that.runEndFunc();
        // 请求悬浮窗权限
        LinFloatWeb.applyPermission(() => {
          LinFloatWeb.destroy("window");
          // 创建悬浮窗
          LinFloatWeb.create(
            {
              id: "window",
              url:
                "file://" +
                plus.io.convertLocalFileSystemURL("_www/static/phoneCall.html"),
              x: (width - 140) * systemInfo.pixelRatio,
              y: (height * systemInfo.pixelRatio) / 2,
              width: 140,
              height: 180,
            },
            (msg) => {
              if (msg.data.todo) {
                let todo = JSON.parse(msg.data.todo);
                if (todo.type == "closeFloatWeb") {
                  that.stopTrtcCloud();
                } else if (todo.type == "changeSound") {
                  // todo 开启关闭免提
                  console.log(todo);
                  if (todo.sound == "sound") {
                    console.log("免提打开");

                    // 免提打开
                    trtcCloud.setAudioRoute(
                      TRTCAudioRoute.TRTCAudioRouteSpeaker
                    );
                  } else {
                    // 听筒打开
                    console.log("听筒打开");
                    trtcCloud.setAudioRoute(
                      TRTCAudioRoute.TRTCAudioRouteEarpiece
                    );
                  }
                }
              }
            }
          );
          LinFloatWeb.show();
        });
      }
    });
    trtcCloud.on("onWarning", async (res) => {
      console.log("- onWarning: ", JSON.stringify(res));
      await that.send_outRoom(that.trtcParms.strRoomId);
      LinFloatWeb.destroy();
      uni.$emit("trtc_quit");
    });
    trtcCloud.on("onError", async (res) => {
      console.log("- onError: ", JSON.stringify(res));
      await that.send_outRoom(that.trtcParms.strRoomId);
      LinFloatWeb.destroy();
      uni.$emit("trtc_quit");
    });
    // 监听 onExitRoom 回调即可获知自己的退房原因
    trtcCloud.on("onExitRoom", async (reason) => {
      await that.send_outRoom(that.trtcParms.strRoomId);
      LinFloatWeb.destroy();
      uni.$emit("trtc_quit");
      console.log(`onExitRoom reason = ${reason}`);
    });
  },
  methods: {
    async get_getUserSign() {
      let res = await getUserSign();
      console.log("999", res);
      if (res.code == 1) {
        this.trtcParms.userId = res.data.userId;
        this.trtcParms.strRoomId = res.data.roomId;
        this.trtcParms.userSig = res.data.UserSign;
        this.trtcParms.sdkAppId =
          this.$store.state.appData.config.tencent.trtc_appId;
      } else {
        this.showMsg(res.msg);
      }
    },
    startLocalPreview(status) {
      // 需要在登入房间之后才能开启视频通话
      const isFrontCamera = false;
      trtcCloud.startLocalPreview(isFrontCamera, this.trtcParms.userId);
      trtcCloud.startLocalAudio(TRTCAudioQuality.TRTCAudioQualitySpeech);
    },
    stopTrtcCloud() {
      trtcCloud.exitRoom();
      LinFloatWeb.destroy();
    },
    async send_outRoom(friendRoom) {
      let res = await outRoom({
        roomId: friendRoom,
      });
      if (res.code == 1) {
        this.showMsg(res.msg);
      } else {
        this.showMsg(res.msg);
      }
    },
    // 第一次打开app 时检查自己房间是否开启   如果后台是开启状态  去做关闭操作
    async onShowCloseRoom() {
      let userId = this.$store.state.userInfo.id;
      let rommId = "room_" + userId;
      let formData = {
        roomId: rommId,
        user_id: userId,
      };
      let res = await checkRoom(formData);
      if (res.code == 1) {
        await that.send_outRoom(res.data.RoomString);
      }
    },
  },
};
